home *** CD-ROM | disk | FTP | other *** search
/ Aminet 6 / Aminet 6 - June 1995.iso / Aminet / dev / gcc / gcc263_src.lha / gcc-2.6.3 / cpp.info-2 < prev    next >
Encoding:
GNU Info File  |  1994-11-19  |  38.6 KB  |  999 lines

  1. This is Info file cpp.info, produced by Makeinfo-1.55 from the input
  2. file cpp.texi.
  3.  
  4.    This file documents the GNU C Preprocessor.
  5.  
  6.    Copyright 1987, 1989, 1991, 1992, 1993, 1994 Free Software
  7. Foundation, Inc.
  8.  
  9.    Permission is granted to make and distribute verbatim copies of this
  10. manual provided the copyright notice and this permission notice are
  11. preserved on all copies.
  12.  
  13.    Permission is granted to copy and distribute modified versions of
  14. this manual under the conditions for verbatim copying, provided also
  15. that the entire resulting derived work is distributed under the terms
  16. of a permission notice identical to this one.
  17.  
  18.    Permission is granted to copy and distribute translations of this
  19. manual into another language, under the above conditions for modified
  20. versions.
  21.  
  22. 
  23. File: cpp.info,  Node: Macro Parentheses,  Next: Swallow Semicolon,  Prev: Misnesting,  Up: Macro Pitfalls
  24.  
  25. Unintended Grouping of Arithmetic
  26. .................................
  27.  
  28.    You may have noticed that in most of the macro definition examples
  29. shown above, each occurrence of a macro argument name had parentheses
  30. around it.  In addition, another pair of parentheses usually surround
  31. the entire macro definition.  Here is why it is best to write macros
  32. that way.
  33.  
  34.    Suppose you define a macro as follows,
  35.  
  36.      #define ceil_div(x, y) (x + y - 1) / y
  37.  
  38. whose purpose is to divide, rounding up.  (One use for this operation is
  39. to compute how many `int' objects are needed to hold a certain number
  40. of `char' objects.)  Then suppose it is used as follows:
  41.  
  42.      a = ceil_div (b & c, sizeof (int));
  43.  
  44. This expands into
  45.  
  46.      a = (b & c + sizeof (int) - 1) / sizeof (int);
  47.  
  48. which does not do what is intended.  The operator-precedence rules of C
  49. make it equivalent to this:
  50.  
  51.      a = (b & (c + sizeof (int) - 1)) / sizeof (int);
  52.  
  53. But what we want is this:
  54.  
  55.      a = ((b & c) + sizeof (int) - 1)) / sizeof (int);
  56.  
  57. Defining the macro as
  58.  
  59.      #define ceil_div(x, y) ((x) + (y) - 1) / (y)
  60.  
  61. provides the desired result.
  62.  
  63.    However, unintended grouping can result in another way.  Consider
  64. `sizeof ceil_div(1, 2)'.  That has the appearance of a C expression
  65. that would compute the size of the type of `ceil_div (1, 2)', but in
  66. fact it means something very different.  Here is what it expands to:
  67.  
  68.      sizeof ((1) + (2) - 1) / (2)
  69.  
  70. This would take the size of an integer and divide it by two.  The
  71. precedence rules have put the division outside the `sizeof' when it was
  72. intended to be inside.
  73.  
  74.    Parentheses around the entire macro definition can prevent such
  75. problems.  Here, then, is the recommended way to define `ceil_div':
  76.  
  77.      #define ceil_div(x, y) (((x) + (y) - 1) / (y))
  78.  
  79. 
  80. File: cpp.info,  Node: Swallow Semicolon,  Next: Side Effects,  Prev: Macro Parentheses,  Up: Macro Pitfalls
  81.  
  82. Swallowing the Semicolon
  83. ........................
  84.  
  85.    Often it is desirable to define a macro that expands into a compound
  86. statement.  Consider, for example, the following macro, that advances a
  87. pointer (the argument `p' says where to find it) across whitespace
  88. characters:
  89.  
  90.      #define SKIP_SPACES (p, limit)  \
  91.      { register char *lim = (limit); \
  92.        while (p != lim) {            \
  93.          if (*p++ != ' ') {          \
  94.            p--; break; }}}
  95.  
  96. Here Backslash-Newline is used to split the macro definition, which must
  97. be a single line, so that it resembles the way such C code would be
  98. laid out if not part of a macro definition.
  99.  
  100.    A call to this macro might be `SKIP_SPACES (p, lim)'.  Strictly
  101. speaking, the call expands to a compound statement, which is a complete
  102. statement with no need for a semicolon to end it.  But it looks like a
  103. function call.  So it minimizes confusion if you can use it like a
  104. function call, writing a semicolon afterward, as in `SKIP_SPACES (p,
  105. lim);'
  106.  
  107.    But this can cause trouble before `else' statements, because the
  108. semicolon is actually a null statement.  Suppose you write
  109.  
  110.      if (*p != 0)
  111.        SKIP_SPACES (p, lim);
  112.      else ...
  113.  
  114. The presence of two statements--the compound statement and a null
  115. statement--in between the `if' condition and the `else' makes invalid C
  116. code.
  117.  
  118.    The definition of the macro `SKIP_SPACES' can be altered to solve
  119. this problem, using a `do ... while' statement.  Here is how:
  120.  
  121.      #define SKIP_SPACES (p, limit)     \
  122.      do { register char *lim = (limit); \
  123.           while (p != lim) {            \
  124.             if (*p++ != ' ') {          \
  125.               p--; break; }}}           \
  126.      while (0)
  127.  
  128.    Now `SKIP_SPACES (p, lim);' expands into
  129.  
  130.      do {...} while (0);
  131.  
  132. which is one statement.
  133.  
  134. 
  135. File: cpp.info,  Node: Side Effects,  Next: Self-Reference,  Prev: Swallow Semicolon,  Up: Macro Pitfalls
  136.  
  137. Duplication of Side Effects
  138. ...........................
  139.  
  140.    Many C programs define a macro `min', for "minimum", like this:
  141.  
  142.      #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
  143.  
  144.    When you use this macro with an argument containing a side effect,
  145. as shown here,
  146.  
  147.      next = min (x + y, foo (z));
  148.  
  149. it expands as follows:
  150.  
  151.      next = ((x + y) < (foo (z)) ? (x + y) : (foo (z)));
  152.  
  153. where `x + y' has been substituted for `X' and `foo (z)' for `Y'.
  154.  
  155.    The function `foo' is used only once in the statement as it appears
  156. in the program, but the expression `foo (z)' has been substituted twice
  157. into the macro expansion.  As a result, `foo' might be called two times
  158. when the statement is executed.  If it has side effects or if it takes
  159. a long time to compute, the results might not be what you intended.  We
  160. say that `min' is an "unsafe" macro.
  161.  
  162.    The best solution to this problem is to define `min' in a way that
  163. computes the value of `foo (z)' only once.  The C language offers no
  164. standard way to do this, but it can be done with GNU C extensions as
  165. follows:
  166.  
  167.      #define min(X, Y)                     \
  168.      ({ typeof (X) __x = (X), __y = (Y);   \
  169.         (__x < __y) ? __x : __y; })
  170.  
  171.    If you do not wish to use GNU C extensions, the only solution is to
  172. be careful when *using* the macro `min'.  For example, you can
  173. calculate the value of `foo (z)', save it in a variable, and use that
  174. variable in `min':
  175.  
  176.      #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
  177.      ...
  178.      {
  179.        int tem = foo (z);
  180.        next = min (x + y, tem);
  181.      }
  182.  
  183. (where we assume that `foo' returns type `int').
  184.  
  185. 
  186. File: cpp.info,  Node: Self-Reference,  Next: Argument Prescan,  Prev: Side Effects,  Up: Macro Pitfalls
  187.  
  188. Self-Referential Macros
  189. .......................
  190.  
  191.    A "self-referential" macro is one whose name appears in its
  192. definition.  A special feature of ANSI Standard C is that the
  193. self-reference is not considered a macro call.  It is passed into the
  194. preprocessor output unchanged.
  195.  
  196.    Let's consider an example:
  197.  
  198.      #define foo (4 + foo)
  199.  
  200. where `foo' is also a variable in your program.
  201.  
  202.    Following the ordinary rules, each reference to `foo' will expand
  203. into `(4 + foo)'; then this will be rescanned and will expand into `(4
  204. + (4 + foo))'; and so on until it causes a fatal error (memory full) in
  205. the preprocessor.
  206.  
  207.    However, the special rule about self-reference cuts this process
  208. short after one step, at `(4 + foo)'.  Therefore, this macro definition
  209. has the possibly useful effect of causing the program to add 4 to the
  210. value of `foo' wherever `foo' is referred to.
  211.  
  212.    In most cases, it is a bad idea to take advantage of this feature.  A
  213. person reading the program who sees that `foo' is a variable will not
  214. expect that it is a macro as well.  The reader will come across the
  215. identifier `foo' in the program and think its value should be that of
  216. the variable `foo', whereas in fact the value is four greater.
  217.  
  218.    The special rule for self-reference applies also to "indirect"
  219. self-reference.  This is the case where a macro X expands to use a
  220. macro `y', and the expansion of `y' refers to the macro `x'.  The
  221. resulting reference to `x' comes indirectly from the expansion of `x',
  222. so it is a self-reference and is not further expanded.  Thus, after
  223.  
  224.      #define x (4 + y)
  225.      #define y (2 * x)
  226.  
  227. `x' would expand into `(4 + (2 * x))'.  Clear?
  228.  
  229.    But suppose `y' is used elsewhere, not from the definition of `x'.
  230. Then the use of `x' in the expansion of `y' is not a self-reference
  231. because `x' is not "in progress".  So it does expand.  However, the
  232. expansion of `x' contains a reference to `y', and that is an indirect
  233. self-reference now because `y' is "in progress".  The result is that
  234. `y' expands to `(2 * (4 + y))'.
  235.  
  236.    It is not clear that this behavior would ever be useful, but it is
  237. specified by the ANSI C standard, so you may need to understand it.
  238.  
  239. 
  240. File: cpp.info,  Node: Argument Prescan,  Next: Cascaded Macros,  Prev: Self-Reference,  Up: Macro Pitfalls
  241.  
  242. Separate Expansion of Macro Arguments
  243. .....................................
  244.  
  245.    We have explained that the expansion of a macro, including the
  246. substituted actual arguments, is scanned over again for macro calls to
  247. be expanded.
  248.  
  249.    What really happens is more subtle: first each actual argument text
  250. is scanned separately for macro calls.  Then the results of this are
  251. substituted into the macro body to produce the macro expansion, and the
  252. macro expansion is scanned again for macros to expand.
  253.  
  254.    The result is that the actual arguments are scanned *twice* to expand
  255. macro calls in them.
  256.  
  257.    Most of the time, this has no effect.  If the actual argument
  258. contained any macro calls, they are expanded during the first scan.
  259. The result therefore contains no macro calls, so the second scan does
  260. not change it.  If the actual argument were substituted as given, with
  261. no prescan, the single remaining scan would find the same macro calls
  262. and produce the same results.
  263.  
  264.    You might expect the double scan to change the results when a
  265. self-referential macro is used in an actual argument of another macro
  266. (*note Self-Reference::.): the self-referential macro would be expanded
  267. once in the first scan, and a second time in the second scan.  But this
  268. is not what happens.  The self-references that do not expand in the
  269. first scan are marked so that they will not expand in the second scan
  270. either.
  271.  
  272.    The prescan is not done when an argument is stringified or
  273. concatenated.  Thus,
  274.  
  275.      #define str(s) #s
  276.      #define foo 4
  277.      str (foo)
  278.  
  279. expands to `"foo"'.  Once more, prescan has been prevented from having
  280. any noticeable effect.
  281.  
  282.    More precisely, stringification and concatenation use the argument as
  283. written, in un-prescanned form.  The same actual argument would be used
  284. in prescanned form if it is substituted elsewhere without
  285. stringification or concatenation.
  286.  
  287.      #define str(s) #s lose(s)
  288.      #define foo 4
  289.      str (foo)
  290.  
  291.    expands to `"foo" lose(4)'.
  292.  
  293.    You might now ask, "Why mention the prescan, if it makes no
  294. difference?  And why not skip it and make the preprocessor faster?"
  295. The answer is that the prescan does make a difference in three special
  296. cases:
  297.  
  298.    * Nested calls to a macro.
  299.  
  300.    * Macros that call other macros that stringify or concatenate.
  301.  
  302.    * Macros whose expansions contain unshielded commas.
  303.  
  304.    We say that "nested" calls to a macro occur when a macro's actual
  305. argument contains a call to that very macro.  For example, if `f' is a
  306. macro that expects one argument, `f (f (1))' is a nested pair of calls
  307. to `f'.  The desired expansion is made by expanding `f (1)' and
  308. substituting that into the definition of `f'.  The prescan causes the
  309. expected result to happen.  Without the prescan, `f (1)' itself would
  310. be substituted as an actual argument, and the inner use of `f' would
  311. appear during the main scan as an indirect self-reference and would not
  312. be expanded.  Here, the prescan cancels an undesirable side effect (in
  313. the medical, not computational, sense of the term) of the special rule
  314. for self-referential macros.
  315.  
  316.    But prescan causes trouble in certain other cases of nested macro
  317. calls.  Here is an example:
  318.  
  319.      #define foo  a,b
  320.      #define bar(x) lose(x)
  321.      #define lose(x) (1 + (x))
  322.      
  323.      bar(foo)
  324.  
  325. We would like `bar(foo)' to turn into `(1 + (foo))', which would then
  326. turn into `(1 + (a,b))'.  But instead, `bar(foo)' expands into
  327. `lose(a,b)', and you get an error because `lose' requires a single
  328. argument.  In this case, the problem is easily solved by the same
  329. parentheses that ought to be used to prevent misnesting of arithmetic
  330. operations:
  331.  
  332.      #define foo (a,b)
  333.      #define bar(x) lose((x))
  334.  
  335.    The problem is more serious when the operands of the macro are not
  336. expressions; for example, when they are statements.  Then parentheses
  337. are unacceptable because they would make for invalid C code:
  338.  
  339.      #define foo { int a, b; ... }
  340.  
  341. In GNU C you can shield the commas using the `({...})' construct which
  342. turns a compound statement into an expression:
  343.  
  344.      #define foo ({ int a, b; ... })
  345.  
  346.    Or you can rewrite the macro definition to avoid such commas:
  347.  
  348.      #define foo { int a; int b; ... }
  349.  
  350.    There is also one case where prescan is useful.  It is possible to
  351. use prescan to expand an argument and then stringify it--if you use two
  352. levels of macros.  Let's add a new macro `xstr' to the example shown
  353. above:
  354.  
  355.      #define xstr(s) str(s)
  356.      #define str(s) #s
  357.      #define foo 4
  358.      xstr (foo)
  359.  
  360.    This expands into `"4"', not `"foo"'.  The reason for the difference
  361. is that the argument of `xstr' is expanded at prescan (because `xstr'
  362. does not specify stringification or concatenation of the argument).
  363. The result of prescan then forms the actual argument for `str'.  `str'
  364. uses its argument without prescan because it performs stringification;
  365. but it cannot prevent or undo the prescanning already done by `xstr'.
  366.  
  367. 
  368. File: cpp.info,  Node: Cascaded Macros,  Next: Newlines in Args,  Prev: Argument Prescan,  Up: Macro Pitfalls
  369.  
  370. Cascaded Use of Macros
  371. ......................
  372.  
  373.    A "cascade" of macros is when one macro's body contains a reference
  374. to another macro.  This is very common practice.  For example,
  375.  
  376.      #define BUFSIZE 1020
  377.      #define TABLESIZE BUFSIZE
  378.  
  379.    This is not at all the same as defining `TABLESIZE' to be `1020'.
  380. The `#define' for `TABLESIZE' uses exactly the body you specify--in
  381. this case, `BUFSIZE'--and does not check to see whether it too is the
  382. name of a macro.
  383.  
  384.    It's only when you *use* `TABLESIZE' that the result of its expansion
  385. is checked for more macro names.
  386.  
  387.    This makes a difference if you change the definition of `BUFSIZE' at
  388. some point in the source file.  `TABLESIZE', defined as shown, will
  389. always expand using the definition of `BUFSIZE' that is currently in
  390. effect:
  391.  
  392.      #define BUFSIZE 1020
  393.      #define TABLESIZE BUFSIZE
  394.      #undef BUFSIZE
  395.      #define BUFSIZE 37
  396.  
  397. Now `TABLESIZE' expands (in two stages) to `37'.  (The `#undef' is to
  398. prevent any warning about the nontrivial redefinition of `BUFSIZE'.)
  399.  
  400. 
  401. File: cpp.info,  Node: Newlines in Args,  Prev: Cascaded Macros,  Up: Macro Pitfalls
  402.  
  403. Newlines in Macro Arguments
  404. ---------------------------
  405.  
  406.    Traditional macro processing carries forward all newlines in macro
  407. arguments into the expansion of the macro.  This means that, if some of
  408. the arguments are substituted more than once, or not at all, or out of
  409. order, newlines can be duplicated, lost, or moved around within the
  410. expansion.  If the expansion consists of multiple statements, then the
  411. effect is to distort the line numbers of some of these statements.  The
  412. result can be incorrect line numbers, in error messages or displayed in
  413. a debugger.
  414.  
  415.    The GNU C preprocessor operating in ANSI C mode adjusts appropriately
  416. for multiple use of an argument--the first use expands all the
  417. newlines, and subsequent uses of the same argument produce no newlines.
  418. But even in this mode, it can produce incorrect line numbering if
  419. arguments are used out of order, or not used at all.
  420.  
  421.    Here is an example illustrating this problem:
  422.  
  423.      #define ignore_second_arg(a,b,c) a; c
  424.      
  425.      ignore_second_arg (foo (),
  426.                         ignored (),
  427.                         syntax error);
  428.  
  429. The syntax error triggered by the tokens `syntax error' results in an
  430. error message citing line four, even though the statement text comes
  431. from line five.
  432.  
  433. 
  434. File: cpp.info,  Node: Conditionals,  Next: Combining Sources,  Prev: Macros,  Up: Top
  435.  
  436. Conditionals
  437. ============
  438.  
  439.    In a macro processor, a "conditional" is a command that allows a part
  440. of the program to be ignored during compilation, on some conditions.
  441. In the C preprocessor, a conditional can test either an arithmetic
  442. expression or whether a name is defined as a macro.
  443.  
  444.    A conditional in the C preprocessor resembles in some ways an `if'
  445. statement in C, but it is important to understand the difference between
  446. them.  The condition in an `if' statement is tested during the execution
  447. of your program.  Its purpose is to allow your program to behave
  448. differently from run to run, depending on the data it is operating on.
  449. The condition in a preprocessor conditional command is tested when your
  450. program is compiled.  Its purpose is to allow different code to be
  451. included in the program depending on the situation at the time of
  452. compilation.
  453.  
  454. * Menu:
  455.  
  456. * Uses: Conditional Uses.       What conditionals are for.
  457. * Syntax: Conditional Syntax.   How conditionals are written.
  458. * Deletion: Deleted Code.       Making code into a comment.
  459. * Macros: Conditionals-Macros.  Why conditionals are used with macros.
  460. * Assertions::                How and why to use assertions.
  461. * Errors: #error Command.       Detecting inconsistent compilation parameters.
  462.  
  463. 
  464. File: cpp.info,  Node: Conditional Uses,  Next: Conditional Syntax,  Up: Conditionals
  465.  
  466. Why Conditionals are Used
  467. -------------------------
  468.  
  469.    Generally there are three kinds of reason to use a conditional.
  470.  
  471.    * A program may need to use different code depending on the machine
  472.      or operating system it is to run on.  In some cases the code for
  473.      one operating system may be erroneous on another operating system;
  474.      for example, it might refer to library routines that do not exist
  475.      on the other system.  When this happens, it is not enough to avoid
  476.      executing the invalid code: merely having it in the program makes
  477.      it impossible to link the program and run it.  With a preprocessor
  478.      conditional, the offending code can be effectively excised from
  479.      the program when it is not valid.
  480.  
  481.    * You may want to be able to compile the same source file into two
  482.      different programs.  Sometimes the difference between the programs
  483.      is that one makes frequent time-consuming consistency checks on its
  484.      intermediate data, or prints the values of those data for
  485.      debugging, while the other does not.
  486.  
  487.    * A conditional whose condition is always false is a good way to
  488.      exclude code from the program but keep it as a sort of comment for
  489.      future reference.
  490.  
  491.    Most simple programs that are intended to run on only one machine
  492. will not need to use preprocessor conditionals.
  493.  
  494. 
  495. File: cpp.info,  Node: Conditional Syntax,  Next: Deleted Code,  Prev: Conditional Uses,  Up: Conditionals
  496.  
  497. Syntax of Conditionals
  498. ----------------------
  499.  
  500.    A conditional in the C preprocessor begins with a "conditional
  501. command": `#if', `#ifdef' or `#ifndef'.  *Note Conditionals-Macros::,
  502. for information on `#ifdef' and `#ifndef'; only `#if' is explained here.
  503.  
  504. * Menu:
  505.  
  506. * If: #if Command.     Basic conditionals using `#if' and `#endif'.
  507. * Else: #else Command. Including some text if the condition fails.
  508. * Elif: #elif Command. Testing several alternative possibilities.
  509.  
  510. 
  511. File: cpp.info,  Node: #if Command,  Next: #else Command,  Up: Conditional Syntax
  512.  
  513. The `#if' Command
  514. .................
  515.  
  516.    The `#if' command in its simplest form consists of
  517.  
  518.      #if EXPRESSION
  519.      CONTROLLED TEXT
  520.      #endif /* EXPRESSION */
  521.  
  522.    The comment following the `#endif' is not required, but it is a good
  523. practice because it helps people match the `#endif' to the
  524. corresponding `#if'.  Such comments should always be used, except in
  525. short conditionals that are not nested.  In fact, you can put anything
  526. at all after the `#endif' and it will be ignored by the GNU C
  527. preprocessor, but only comments are acceptable in ANSI Standard C.
  528.  
  529.    EXPRESSION is a C expression of integer type, subject to stringent
  530. restrictions.  It may contain
  531.  
  532.    * Integer constants, which are all regarded as `long' or `unsigned
  533.      long'.
  534.  
  535.    * Character constants, which are interpreted according to the
  536.      character set and conventions of the machine and operating system
  537.      on which the preprocessor is running.  The GNU C preprocessor uses
  538.      the C data type `char' for these character constants; therefore,
  539.      whether some character codes are negative is determined by the C
  540.      compiler used to compile the preprocessor.  If it treats `char' as
  541.      signed, then character codes large enough to set the sign bit will
  542.      be considered negative; otherwise, no character code is considered
  543.      negative.
  544.  
  545.    * Arithmetic operators for addition, subtraction, multiplication,
  546.      division, bitwise operations, shifts, comparisons, and logical
  547.      operations (`&&' and `||').
  548.  
  549.    * Identifiers that are not macros, which are all treated as zero(!).
  550.  
  551.    * Macro calls.  All macro calls in the expression are expanded before
  552.      actual computation of the expression's value begins.
  553.  
  554.    Note that `sizeof' operators and `enum'-type values are not allowed.
  555. `enum'-type values, like all other identifiers that are not taken as
  556. macro calls and expanded, are treated as zero.
  557.  
  558.    The CONTROLLED TEXT inside of a conditional can include preprocessor
  559. commands.  Then the commands inside the conditional are obeyed only if
  560. that branch of the conditional succeeds.  The text can also contain
  561. other conditional groups.  However, the `#if' and `#endif' commands
  562. must balance.
  563.  
  564. 
  565. File: cpp.info,  Node: #else Command,  Next: #elif Command,  Prev: #if Command,  Up: Conditional Syntax
  566.  
  567. The `#else' Command
  568. ...................
  569.  
  570.    The `#else' command can be added to a conditional to provide
  571. alternative text to be used if the condition is false.  This is what it
  572. looks like:
  573.  
  574.      #if EXPRESSION
  575.      TEXT-IF-TRUE
  576.      #else /* Not EXPRESSION */
  577.      TEXT-IF-FALSE
  578.      #endif /* Not EXPRESSION */
  579.  
  580.    If EXPRESSION is nonzero, and thus the TEXT-IF-TRUE is active, then
  581. `#else' acts like a failing conditional and the TEXT-IF-FALSE is
  582. ignored.  Contrariwise, if the `#if' conditional fails, the
  583. TEXT-IF-FALSE is considered included.
  584.  
  585. 
  586. File: cpp.info,  Node: #elif Command,  Prev: #else Command,  Up: Conditional Syntax
  587.  
  588. The `#elif' Command
  589. ...................
  590.  
  591.    One common case of nested conditionals is used to check for more
  592. than two possible alternatives.  For example, you might have
  593.  
  594.      #if X == 1
  595.      ...
  596.      #else /* X != 1 */
  597.      #if X == 2
  598.      ...
  599.      #else /* X != 2 */
  600.      ...
  601.      #endif /* X != 2 */
  602.      #endif /* X != 1 */
  603.  
  604.    Another conditional command, `#elif', allows this to be abbreviated
  605. as follows:
  606.  
  607.      #if X == 1
  608.      ...
  609.      #elif X == 2
  610.      ...
  611.      #else /* X != 2 and X != 1*/
  612.      ...
  613.      #endif /* X != 2 and X != 1*/
  614.  
  615.    `#elif' stands for "else if".  Like `#else', it goes in the middle
  616. of a `#if'-`#endif' pair and subdivides it; it does not require a
  617. matching `#endif' of its own.  Like `#if', the `#elif' command includes
  618. an expression to be tested.
  619.  
  620.    The text following the `#elif' is processed only if the original
  621. `#if'-condition failed and the `#elif' condition succeeds.  More than
  622. one `#elif' can go in the same `#if'-`#endif' group.  Then the text
  623. after each `#elif' is processed only if the `#elif' condition succeeds
  624. after the original `#if' and any previous `#elif' commands within it
  625. have failed.  `#else' is equivalent to `#elif 1', and `#else' is
  626. allowed after any number of `#elif' commands, but `#elif' may not follow
  627. `#else'.
  628.  
  629. 
  630. File: cpp.info,  Node: Deleted Code,  Next: Conditionals-Macros,  Prev: Conditional Syntax,  Up: Conditionals
  631.  
  632. Keeping Deleted Code for Future Reference
  633. -----------------------------------------
  634.  
  635.    If you replace or delete a part of the program but want to keep the
  636. old code around as a comment for future reference, the easy way to do
  637. this is to put `#if 0' before it and `#endif' after it.  This is better
  638. than using comment delimiters `/*' and `*/' since those won't work if
  639. the code already contains comments (C comments do not nest).
  640.  
  641.    This works even if the code being turned off contains conditionals,
  642. but they must be entire conditionals (balanced `#if' and `#endif').
  643.  
  644.    Conversely, do not use `#if 0' for comments which are not C code.
  645. Use the comment delimiters `/*' and `*/' instead.  The interior of `#if
  646. 0' must consist of complete tokens; in particular, singlequote
  647. characters must balance.  But comments often contain unbalanced
  648. singlequote characters (known in English as apostrophes).  These
  649. confuse `#if 0'.  They do not confuse `/*'.
  650.  
  651. 
  652. File: cpp.info,  Node: Conditionals-Macros,  Next: Assertions,  Prev: Deleted Code,  Up: Conditionals
  653.  
  654. Conditionals and Macros
  655. -----------------------
  656.  
  657.    Conditionals are useful in connection with macros or assertions,
  658. because those are the only ways that an expression's value can vary
  659. from one compilation to another.  A `#if' command whose expression uses
  660. no macros or assertions is equivalent to `#if 1' or `#if 0'; you might
  661. as well determine which one, by computing the value of the expression
  662. yourself, and then simplify the program.
  663.  
  664.    For example, here is a conditional that tests the expression
  665. `BUFSIZE == 1020', where `BUFSIZE' must be a macro.
  666.  
  667.      #if BUFSIZE == 1020
  668.        printf ("Large buffers!\n");
  669.      #endif /* BUFSIZE is large */
  670.  
  671.    (Programmers often wish they could test the size of a variable or
  672. data type in `#if', but this does not work.  The preprocessor does not
  673. understand `sizeof', or typedef names, or even the type keywords such
  674. as `int'.)
  675.  
  676.    The special operator `defined' is used in `#if' expressions to test
  677. whether a certain name is defined as a macro.  Either `defined NAME' or
  678. `defined (NAME)' is an expression whose value is 1 if NAME is defined
  679. as macro at the current point in the program, and 0 otherwise.  For the
  680. `defined' operator it makes no difference what the definition of the
  681. macro is; all that matters is whether there is a definition.  Thus, for
  682. example,
  683.  
  684.      #if defined (vax) || defined (ns16000)
  685.  
  686. would succeed if either of the names `vax' and `ns16000' is defined as
  687. a macro.  You can test the same condition using assertions (*note
  688. Assertions::.), like this:
  689.  
  690.      #if #cpu (vax) || #cpu (ns16000)
  691.  
  692.    If a macro is defined and later undefined with `#undef', subsequent
  693. use of the `defined' operator returns 0, because the name is no longer
  694. defined.  If the macro is defined again with another `#define',
  695. `defined' will recommence returning 1.
  696.  
  697.    Conditionals that test whether just one name is defined are very
  698. common, so there are two special short conditional commands for this
  699. case.
  700.  
  701. `#ifdef NAME'
  702.      is equivalent to `#if defined (NAME)'.
  703.  
  704. `#ifndef NAME'
  705.      is equivalent to `#if ! defined (NAME)'.
  706.  
  707.    Macro definitions can vary between compilations for several reasons.
  708.  
  709.    * Some macros are predefined on each kind of machine.  For example,
  710.      on a Vax, the name `vax' is a predefined macro.  On other
  711.      machines, it would not be defined.
  712.  
  713.    * Many more macros are defined by system header files.  Different
  714.      systems and machines define different macros, or give them
  715.      different values.  It is useful to test these macros with
  716.      conditionals to avoid using a system feature on a machine where it
  717.      is not implemented.
  718.  
  719.    * Macros are a common way of allowing users to customize a program
  720.      for different machines or applications.  For example, the macro
  721.      `BUFSIZE' might be defined in a configuration file for your
  722.      program that is included as a header file in each source file.  You
  723.      would use `BUFSIZE' in a preprocessor conditional in order to
  724.      generate different code depending on the chosen configuration.
  725.  
  726.    * Macros can be defined or undefined with `-D' and `-U' command
  727.      options when you compile the program.  You can arrange to compile
  728.      the same source file into two different programs by choosing a
  729.      macro name to specify which program you want, writing conditionals
  730.      to test whether or how this macro is defined, and then controlling
  731.      the state of the macro with compiler command options.  *Note
  732.      Invocation::.
  733.  
  734.    Assertions are usually predefined, but can be defined with
  735. preprocessor commands or command-line options.
  736.  
  737. 
  738. File: cpp.info,  Node: Assertions,  Next: #error Command,  Prev: Conditionals-Macros,  Up: Conditionals
  739.  
  740. Assertions
  741. ----------
  742.  
  743.    "Assertions" are a more systematic alternative to macros in writing
  744. conditionals to test what sort of computer or system the compiled
  745. program will run on.  Assertions are usually predefined, but you can
  746. define them with preprocessor commands or command-line options.
  747.  
  748.    The macros traditionally used to describe the type of target are not
  749. classified in any way according to which question they answer; they may
  750. indicate a hardware architecture, a particular hardware model, an
  751. operating system, a particular version of an operating system, or
  752. specific configuration options.  These are jumbled together in a single
  753. namespace.  In contrast, each assertion consists of a named question and
  754. an answer.  The question is usually called the "predicate".  An
  755. assertion looks like this:
  756.  
  757.      #PREDICATE (ANSWER)
  758.  
  759. You must use a properly formed identifier for PREDICATE.  The value of
  760. ANSWER can be any sequence of words; all characters are significant
  761. except for leading and trailing whitespace, and differences in internal
  762. whitespace sequences are ignored.  Thus, `x + y' is different from
  763. `x+y' but equivalent to `x + y'.  `)' is not allowed in an answer.
  764.  
  765.    Here is a conditional to test whether the answer ANSWER is asserted
  766. for the predicate PREDICATE:
  767.  
  768.      #if #PREDICATE (ANSWER)
  769.  
  770. There may be more than one answer asserted for a given predicate.  If
  771. you omit the answer, you can test whether *any* answer is asserted for
  772. PREDICATE:
  773.  
  774.      #if #PREDICATE
  775.  
  776.    Most of the time, the assertions you test will be predefined
  777. assertions.  GNU C provides three predefined predicates: `system',
  778. `cpu', and `machine'.  `system' is for assertions about the type of
  779. software, `cpu' describes the type of computer architecture, and
  780. `machine' gives more information about the computer.  For example, on a
  781. GNU system, the following assertions would be true:
  782.  
  783.      #system (gnu)
  784.      #system (mach)
  785.      #system (mach 3)
  786.      #system (mach 3.SUBVERSION)
  787.      #system (hurd)
  788.      #system (hurd VERSION)
  789.  
  790. and perhaps others.  The alternatives with more or less version
  791. information let you ask more or less detailed questions about the type
  792. of system software.
  793.  
  794.    On a Unix system, you would find `#system (unix)' and perhaps one of:
  795. `#system (aix)', `#system (bsd)', `#system (hpux)', `#system (lynx)',
  796. `#system (mach)', `#system (posix)', `#system (svr3)', `#system
  797. (svr4)', or `#system (xpg4)' with possible version numbers following.
  798.  
  799.    Other values for `system' are `#system (mvs)' and `#system (vms)'.
  800.  
  801.    *Portability note:* Many Unix C compilers provide only one answer
  802. for the `system' assertion: `#system (unix)', if they support
  803. assertions at all.  This is less than useful.
  804.  
  805.    An assertion with a multi-word answer is completely different from
  806. several assertions with individual single-word answers.  For example,
  807. the presence of `system (mach 3.0)' does not mean that `system (3.0)'
  808. is true.  It also does not directly imply `system (mach)', but in GNU
  809. C, that last will normally be asserted as well.
  810.  
  811.    The current list of possible assertion values for `cpu' is: `#cpu
  812. (a29k)', `#cpu (alpha)', `#cpu (arm)', `#cpu (clipper)', `#cpu
  813. (convex)', `#cpu (elxsi)', `#cpu (tron)', `#cpu (h8300)', `#cpu
  814. (i370)', `#cpu (i386)', `#cpu (i860)', `#cpu (i960)', `#cpu (m68k)',
  815. `#cpu (m88k)', `#cpu (mips)', `#cpu (ns32k)', `#cpu (hppa)', `#cpu
  816. (pyr)', `#cpu (ibm032)', `#cpu (rs6000)', `#cpu (sh)', `#cpu (sparc)',
  817. `#cpu (spur)', `#cpu (tahoe)', `#cpu (vax)', `#cpu (we32000)'.
  818.  
  819.    You can create assertions within a C program using `#assert', like
  820. this:
  821.  
  822.      #assert PREDICATE (ANSWER)
  823.  
  824. (Note the absence of a `#' before PREDICATE.)
  825.  
  826.    Each time you do this, you assert a new true answer for PREDICATE.
  827. Asserting one answer does not invalidate previously asserted answers;
  828. they all remain true.  The only way to remove an assertion is with
  829. `#unassert'.  `#unassert' has the same syntax as `#assert'.  You can
  830. also remove all assertions about PREDICATE like this:
  831.  
  832.      #unassert PREDICATE
  833.  
  834.    You can also add or cancel assertions using command options when you
  835. run `gcc' or `cpp'.  *Note Invocation::.
  836.  
  837. 
  838. File: cpp.info,  Node: #error Command,  Prev: Assertions,  Up: Conditionals
  839.  
  840. The `#error' and `#warning' Commands
  841. ------------------------------------
  842.  
  843.    The command `#error' causes the preprocessor to report a fatal
  844. error.  The rest of the line that follows `#error' is used as the error
  845. message.
  846.  
  847.    You would use `#error' inside of a conditional that detects a
  848. combination of parameters which you know the program does not properly
  849. support.  For example, if you know that the program will not run
  850. properly on a Vax, you might write
  851.  
  852.      #ifdef __vax__
  853.      #error Won't work on Vaxen.  See comments at get_last_object.
  854.      #endif
  855.  
  856. *Note Nonstandard Predefined::, for why this works.
  857.  
  858.    If you have several configuration parameters that must be set up by
  859. the installation in a consistent way, you can use conditionals to detect
  860. an inconsistency and report it with `#error'.  For example,
  861.  
  862.      #if HASH_TABLE_SIZE % 2 == 0 || HASH_TABLE_SIZE % 3 == 0 \
  863.          || HASH_TABLE_SIZE % 5 == 0
  864.      #error HASH_TABLE_SIZE should not be divisible by a small prime
  865.      #endif
  866.  
  867.    The command `#warning' is like the command `#error', but causes the
  868. preprocessor to issue a warning and continue preprocessing.  The rest of
  869. the line that follows `#warning' is used as the warning message.
  870.  
  871.    You might use `#warning' in obsolete header files, with a message
  872. directing the user to the header file which should be used instead.
  873.  
  874. 
  875. File: cpp.info,  Node: Combining Sources,  Next: Other Commands,  Prev: Conditionals,  Up: Top
  876.  
  877. Combining Source Files
  878. ======================
  879.  
  880.    One of the jobs of the C preprocessor is to inform the C compiler of
  881. where each line of C code came from: which source file and which line
  882. number.
  883.  
  884.    C code can come from multiple source files if you use `#include';
  885. both `#include' and the use of conditionals and macros can cause the
  886. line number of a line in the preprocessor output to be different from
  887. the line's number in the original source file.  You will appreciate the
  888. value of making both the C compiler (in error messages) and symbolic
  889. debuggers such as GDB use the line numbers in your source file.
  890.  
  891.    The C preprocessor builds on this feature by offering a command by
  892. which you can control the feature explicitly.  This is useful when a
  893. file for input to the C preprocessor is the output from another program
  894. such as the `bison' parser generator, which operates on another file
  895. that is the true source file.  Parts of the output from `bison' are
  896. generated from scratch, other parts come from a standard parser file.
  897. The rest are copied nearly verbatim from the source file, but their
  898. line numbers in the `bison' output are not the same as their original
  899. line numbers.  Naturally you would like compiler error messages and
  900. symbolic debuggers to know the original source file and line number of
  901. each line in the `bison' input.
  902.  
  903.    `bison' arranges this by writing `#line' commands into the output
  904. file.  `#line' is a command that specifies the original line number and
  905. source file name for subsequent input in the current preprocessor input
  906. file.  `#line' has three variants:
  907.  
  908. `#line LINENUM'
  909.      Here LINENUM is a decimal integer constant.  This specifies that
  910.      the line number of the following line of input, in its original
  911.      source file, was LINENUM.
  912.  
  913. `#line LINENUM FILENAME'
  914.      Here LINENUM is a decimal integer constant and FILENAME is a
  915.      string constant.  This specifies that the following line of input
  916.      came originally from source file FILENAME and its line number there
  917.      was LINENUM.  Keep in mind that FILENAME is not just a file name;
  918.      it is surrounded by doublequote characters so that it looks like a
  919.      string constant.
  920.  
  921. `#line ANYTHING ELSE'
  922.      ANYTHING ELSE is checked for macro calls, which are expanded.  The
  923.      result should be a decimal integer constant followed optionally by
  924.      a string constant, as described above.
  925.  
  926.    `#line' commands alter the results of the `__FILE__' and `__LINE__'
  927. predefined macros from that point on.  *Note Standard Predefined::.
  928.  
  929.    The output of the preprocessor (which is the input for the rest of
  930. the compiler) contains commands that look much like `#line' commands.
  931. They start with just `#' instead of `#line', but this is followed by a
  932. line number and file name as in `#line'.  *Note Output::.
  933.  
  934. 
  935. File: cpp.info,  Node: Other Commands,  Next: Output,  Prev: Combining Sources,  Up: Top
  936.  
  937. Miscellaneous Preprocessor Commands
  938. ===================================
  939.  
  940.    This section describes three additional preprocessor commands.  They
  941. are not very useful, but are mentioned for completeness.
  942.  
  943.    The "null command" consists of a `#' followed by a Newline, with
  944. only whitespace (including comments) in between.  A null command is
  945. understood as a preprocessor command but has no effect on the
  946. preprocessor output.  The primary significance of the existence of the
  947. null command is that an input line consisting of just a `#' will
  948. produce no output, rather than a line of output containing just a `#'.
  949. Supposedly some old C programs contain such lines.
  950.  
  951.    The ANSI standard specifies that the `#pragma' command has an
  952. arbitrary, implementation-defined effect.  In the GNU C preprocessor,
  953. `#pragma' commands are not used, except for `#pragma once' (*note
  954. Once-Only::.).  However, they are left in the preprocessor output, so
  955. they are available to the compilation pass.
  956.  
  957.    The `#ident' command is supported for compatibility with certain
  958. other systems.  It is followed by a line of text.  On some systems, the
  959. text is copied into a special place in the object file; on most systems,
  960. the text is ignored and this command has no effect.  Typically `#ident'
  961. is only used in header files supplied with those systems where it is
  962. meaningful.
  963.  
  964. 
  965. File: cpp.info,  Node: Output,  Next: Invocation,  Prev: Other Commands,  Up: Top
  966.  
  967. C Preprocessor Output
  968. =====================
  969.  
  970.    The output from the C preprocessor looks much like the input, except
  971. that all preprocessor command lines have been replaced with blank lines
  972. and all comments with spaces.  Whitespace within a line is not altered;
  973. however, a space is inserted after the expansions of most macro calls.
  974.  
  975.    Source file name and line number information is conveyed by lines of
  976. the form
  977.  
  978.      # LINENUM FILENAME FLAGS
  979.  
  980. which are inserted as needed into the middle of the input (but never
  981. within a string or character constant).  Such a line means that the
  982. following line originated in file FILENAME at line LINENUM.
  983.  
  984.    After the file name comes zero or more flags, which are `1', `2' or
  985. `3'.  If there are multiple flags, spaces separate them.  Here is what
  986. the flags mean:
  987.  
  988. `1'
  989.      This indicates the start of a new file.
  990.  
  991. `2'
  992.      This indicates returning to a file (after having included another
  993.      file).
  994.  
  995. `3'
  996.      This indicates that the following text comes from a system header
  997.      file, so certain warnings should be suppressed.
  998.  
  999.